#!/usr/bin/env python
# -*- coding:utf-8 -*-
import configparser
import os

import bottle
from bottle import Bottle, request, response

f = r'setting.ini'
config = configparser.RawConfigParser()
config.read(f, encoding='UTF8')

file = Bottle()

mimeTypes = [
    'text/csv', 'text/plain', 'application/csv', 'text/comma-separated-values',
    'application/excel', 'application/vnd.ms-excel', 'application/vnd.msexcel',
    'text/anytext', 'application/octet-stream', 'application/txt'
]


@file.hook('before_request')
def validate():
    REQUEST_METHOD = request.environ.get('REQUEST_METHOD')
    HTTP_ACCESS_CONTROL_REQUEST_METHOD = request.environ.get('HTTP_ACCESS_CONTROL_REQUEST_METHOD')
    if REQUEST_METHOD == 'OPTIONS' and HTTP_ACCESS_CONTROL_REQUEST_METHOD:
        request.environ['REQUEST_METHOD'] = HTTP_ACCESS_CONTROL_REQUEST_METHOD


@file.hook('after_request')
def enable_cors():
    response.headers['Access-Control-Allow-Origin'] = '*'  # 允许所有域名的请求
    response.headers['Access-Control-Allow-Methods'] = 'GET, POST, DELETE, PUT, HEAD, OPTIONS'
    response.headers['Access-Control-Allow-Headers'] = 'origin,content-type,accept,authorization,x-requested-with'
    response.headers["Access-Control-Allow-Credentials"] = "true"
    response.headers['Access-Control-Max-Age'] = 86400
    response.status = 200


# 微品传送门业务
class FileRoute:

    # 图片类静态文件请求
    @staticmethod
    @file.get('/img/<filename>')
    def send_image(filename):
        from bottle import static_file
        _root = config['upload']['file_path']
        return static_file(filename, root=_root, mimetype='image/png')

    # 一般静态文件请求
    @staticmethod
    @file.get('/statics/<filename:path>')
    def send_static(filename):
        from bottle import static_file
        _root = config['upload']['file_path']
        return static_file(filename, root=_root)

    # 一般静态文件请求
    @staticmethod
    @file.get('/download/<filename:path>')
    def send_static(filename):
        from bottle import static_file
        _root = config['download']['file_path']
        return static_file(filename=filename, root=_root, download=True)

    @staticmethod
    @file.route('/static/<filepath:path>')
    def server_static(filepath):
        return bottle.static_file(filepath, root='static')

    # ------------------------------------------------------------------------------------------------------------------
    @staticmethod
    @file.post('/upload/posts')
    def do_upload():
        from os.path import exists as file_exists
        str = 'tran'
        emp = True
        items = []
        for name, item in request.POST.allitems():
            if isinstance(item, bottle.FileUpload):
                items.append(item)
                emp = False
        if emp:
            return {'code': 500, 'data': {}, 'message': '上传文件不存在，请检查文件是否正确'}
        res = []
        for file in items:
            name, ext = os.path.splitext(file.filename)
            if ext not in ('.png', '.jpg', '.jpeg'):
                return {'code': 500, 'data': {}, 'message': 'File extension not allowed.only support .png, .jpg, .jpeg'}
            save_path = FileRoute.get_save_path_for_category(str)
            if not file_exists(save_path):
                os.makedirs(save_path)
            save_file = save_path + file.raw_filename
            if file_exists(save_file):
                os.remove(save_file)
            try:
                file.save(save_file)  # appends upload.filename automatically
            except OSError as error:
                print(error)
            res.append({"name": file.raw_filename, "url": config['upload']['file_server'] + file.raw_filename})
        return {'code': 200, 'data': res, 'message': ''}

    @staticmethod
    @file.post('/upload/pic')
    def do_upload():
        from os.path import exists as file_exists
        str = 'tran'
        file = request.files.get("files")
        if file is None:
            return {'code': 500, 'data': {}, 'message': '上传文件不存在，请检查文件是否正确'}
        name, ext = os.path.splitext(file.filename)
        if ext not in ('.png', '.jpg', '.jpeg'):
            return {'code': 500, 'data': {}, 'message': 'File extension not allowed.only support .png, .jpg, .jpeg'}
        save_path = FileRoute.get_save_path_for_category(str)
        if not file_exists(save_path):
            os.makedirs(save_path)

        save_file = save_path + file.raw_filename
        if file_exists(save_file):
            os.remove(save_file)
        try:
            file.save(save_file)  # appends upload.filename automatically
        except OSError as error:
            print(error)
        return {'code': 200, 'data': {
            "url": config['upload']['file_server'] + file.raw_filename,
            "save_path": save_path,
            "content_type": file.content_type,
            "save_file_name": file.raw_filename,
        }, 'message': ''}

    @staticmethod
    @file.post('/upload/big')
    def do_upload():
        import datetime
        from os.path import exists as file_exists
        str = 'tran'
        file = request.files.get("files")
        chunk = request.forms.get("chunk")
        try:
            if file is None:
                return {'code': 500, 'data': {}, 'message': '上传文件不存在，请检查文件是否正确'}

            # 存在目录判定
            name, ext = os.path.splitext(file.filename)
            save_path = FileRoute.get_save_path_for_category(str)
            if not file_exists(save_path):
                os.makedirs(save_path)
            # 配置文件名称,去掉中文名称
            now = datetime.datetime.now()
            str_time = now.strftime("%Y%m%d%H%M%S")
            new_file_name = str_time + "%s" % ext
            save_file = (save_path + new_file_name)
            if int(chunk) == 0:
                file.save(save_file, overwrite=True, section_upload=False)  # appends upload.filename automatically
            file.save(save_file, overwrite=True, section_upload=True)  # appends upload.filename automatically
        except OSError as error:
            print(error)
        return {'code': 200, 'data': {
            "url": config['upload']['file_server'] + new_file_name,
            "save_path": save_file,
            "content_type": file.content_type,
            "save_file_name": new_file_name,
        }, 'message': ''}

    @staticmethod
    @file.post('/upload/xls')
    def do_upload():
        import datetime
        from os.path import exists as file_exists
        str = 'tran'
        info = request.forms.get("info")
        file = request.files.get("files")
        try:
            if file is None:
                return {'code': 500, 'data': {}, 'message': '上传文件不存在，请检查文件是否正确'}
            # 存在目录判定
            name, ext = os.path.splitext(file.filename)
            save_path = FileRoute.get_save_path_for_category(str)
            if not file_exists(save_path):
                os.makedirs(save_path)
            # 配置文件名称,去掉中文名称
            now = datetime.datetime.now()
            str_time = now.strftime("%Y%m%d%H%M%S")
            new_file_name = str_time + "%s" % ext
            save_file = (save_path + new_file_name)
            if file_exists(save_file):
                os.remove(save_file)
            file.save(save_file, overwrite=True)  # appends upload.filename automatically
        except OSError as error:
            print(error)
        return {'code': 200, 'data': {
            "dataId": str_time,
            "url": config['upload']['file_server'] + new_file_name,
            "save_path": save_file,
            "content_type": file.content_type,
            "save_file_name": new_file_name,
        }, 'message': ''}

    @staticmethod
    @file.post('/upload')
    def do_upload():
        import datetime
        from os.path import exists as file_exists
        str = 'tran'
        file = request.files.get("files")
        try:
            if file is None:
                return {'code': 500, 'data': {}, 'message': '上传文件不存在，请检查文件是否正确'}

            # 存在目录判定
            name, ext = os.path.splitext(file.filename)
            save_path = FileRoute.get_save_path_for_category(str)
            if not file_exists(save_path):
                os.makedirs(save_path)
            # 配置文件名称,去掉中文名称
            now = datetime.datetime.now()
            str_time = now.strftime("%Y%m%d%H%M%S")
            new_file_name = str_time + "%s" % ext
            save_file = (save_path + new_file_name)
            if file_exists(save_file):
                os.remove(save_file)
            file.save(save_file, overwrite=True, section_upload=False)  # appends upload.filename automatically
        except OSError as error:
            print(error)
        return {'code': 200, 'data': {
            "url": config['upload']['file_server'] + new_file_name,
            "save_path": save_file,
            "content_type": file.content_type,
            "save_file_name": new_file_name,
        }, 'message': ''}

    def get_save_path_for_category(str):
        return config['upload']['file_path']
